<?php
namespace app\api\controller;

use app\api\cache\KeysUtil;
use app\api\cache\RedisCache;
use app\api\logic\OrderLogic;
use app\api\logic\ServiceLogic;
use app\common\controller\RestController;
use app\common\models\Community\CommunityTasksLog;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Order extends RestController
{
    protected $noNeedLogin = [
        // 'orderDetail', 'orderExpress', 'changeAddress',
    ];

    /**
     * 确认收货
     * @return [type] [description]
     */
    public function taskOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = OrderLogic::getInstance()->taskOrder($orderNo);
        return $this->result($info);
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function orderDetail(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = OrderLogic::getInstance()->orderDetail($orderNo);
        // 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        $status = $info['orderInfo']['status'];
        // $status = 1;
        if ($status == 1) {
            $tips     = ['仓库处理中 预计在2个工昨日内发货'];
            $createAt = $info['orderInfo']['createAt'];
            $date     = new \DateTime($createAt);
            $date->modify('+2 day');
            $diff = strtotime($createAt) + 172800;
            $now  = time();
            if ($now > $diff) {
                $tips[] = '1预计' . $date->format('n月j日') . '24:00前发货，' . OrderLogic::getInstance()->estimatedDelivery(
                    $info['orderShop'][0]['shopId'] ?? '',
                    $info['orderAddress']['city'] ?? '',
                    $date,
                    3
                );
            } else {
                $tips[] = '预计' . $date->format('n月j日') . '24:00前发货，' . OrderLogic::getInstance()->estimatedDelivery(
                    $info['orderShop'][0]['shopId'] ?? '',
                    $info['orderAddress']['city'] ?? '',
                    $date,
                    4
                );
            }
            $info['tips'] = $tips;
        } else if ($status == 2) {
            $goodsId = $info['orderShop'][0]['goodsInfo'][0]['goodsId'] ?? 0;
            // var_dump($goodsId);exit;
            $express = \app\api\services\OrderService::getInstance()->orderExpress(
                $orderNo,
                $goodsId);
            // echo json_encode($express, 320);exit;
            $info['tips'] = empty($express['expressList'][0]) ? [] : [
                $express['expressList'][0] ?? [],
            ];
            // $info['tips'] = [{"time":"2024-01-15 21:20:54","context":"已签收，签收人凭取货码签收。起早贪黑不停忙，如有不妥您见谅，好评激励我向上，求个五星暖心房。","ftime":"2024-01-15 21:20:54","areaCode":null,"areaName":null,"status":"签收"}]
        } else {
            $info['tips'] = [];
        }
        if (in_array($status, [5, 6])) {
            $userinfo = \think\App::getInstance()->userinfo;
            // idx_UserId_OrdereNo_OrderGoodsId
            $refund = \think\facade\Db::table('order_refund')
                ->field(['status', 'refund_money', 'refuse_desc', 'auth_time'])
                ->where('user_id', $userinfo->id)
                ->where('order_no', $orderNo)
                ->order('order_refund_id desc')
                ->find();
            $info['refundStatus'] = $refund['status'];
            $info['refuseDesc']   = $refund['refuse_desc'];
            $info['refuseMoney']  = $refund['refund_money'];
            $info['authTime']     = $refund['auth_time'];
            // $info['processes'] = OrderRefundLogic::getInstance()->processe($info['refundStatus']);
        }
        $where = [
            ['order_no','=',$orderNo],
        ];
        $count = CommunityTasksLog::getInstance()->where($where)->count();
        $info['isCommunity'] = 0;
        return $this->result($info);
    }

    public function orderExpress(): bool
    {
        $orderNo = input('orderNo', 0);
        $goodsId = input('goodsId', 0);
        $info    = OrderLogic::getInstance()->orderExpress($orderNo, $goodsId);
        return $this->result($info);
    }

    /**
     * @return bool
     */
    public function delOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = OrderLogic::getInstance()->delOrder($orderNo);
        return $this->result($info);
    }

    /**
     * 取消并退款
     * @param $orderNo
     * @return bool
     */
    public function cancelOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = OrderLogic::getInstance()->cancelOrder($orderNo);
        return $this->result($info);
    }

    /**
     * 取消不需要退款
     * @param $orderNo
     * @return bool
     */
    public function cancellationOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = OrderLogic::getInstance()->cancellationOrder($orderNo);
        return $this->result($info);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderList(): bool
    {
        $page      = input('page', 1);
        $pageSize  = input('pageSize', 10);
        $type      = input('type', 1);
        $orderType = input('orderType', 2);
        $info      = OrderLogic::getInstance()->orderList($type, $orderType, $page, $pageSize);
        return $this->result($info);
    }

    /**
     * 订单预览
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderPreview(): bool
    {
        $goodsInfo = input('goodsInfo', '');
        $addressId = input('addressId', 0);
        $couponId  = input('couponId', '');
        $info      = OrderLogic::getInstance()->orderPreview($goodsInfo, $couponId);

        // echo $this->result($info['rows'][0]['shopInfo']);exit;
        $info['tips'] = OrderLogic::getInstance()->estimatedDelivery(
            $info['rows'][0]['shopInfo']['sendCity'] ?? '',
            $addressId,
        );
        return $this->result($info);
    }

    /**
     * 线下店下单接口
     * @return [type] [description]
     */
    public function createOutlineOrder(): bool
    {
        $shopId = input('shopId', 0);
        // 使用优惠类型：  coupon | discount | coupon_discount | '' 空字符串表示不需要优惠
        $useSale  = input('useSale', '');
        $couponId = input('couponId', '');
        $price    = input('price', 0);
        $payPrice    = input('payPrice', 0);
        $skuId    = input('skuID', input('skuId', 0));
        $deduction = input('deduction',0);
        // var_dump($skuId);exit;
        $info = OrderLogic::getInstance()->createOutlineOrder(
            $shopId,
            $price,
            intval($skuId),
            $couponId,
            [
                'useSale' => $useSale,
            ],
            $deduction,
            $payPrice
        );
        return $this->result($info);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createOrder(): bool
    {
        $goodsInfo = input('goodsInfo', '');
        $addressId = input('addressId', 0);
        $couponId  = input('couponId', 0);
        $price     = input('price', 0);
        $amount    = input('amount', 0);
        $orderType = input('orderType', 1);
        // 使用优惠类型：  coupon | discount | coupon_discount | '' 空字符串表示不需要优惠
        $useSale   = input('useSale', '');
        $userNotes = input('userNote', '');
        //自提
        $takeMobile = input('takeMobile','');
        $takeTime = input('takeTime','');
        $serviceId = input('serviceId',0);
        $deduction = input('deduction',0);
        if (empty($userNotes)) {
            // 下两个版本可以删除 这个 if block ，兼容之前逻辑 2024-05-24
            $userNotes = input('leaveWord', '');
        }
        $info = OrderLogic::getInstance()->createOrder(
            $goodsInfo,
            $addressId,
            $orderType,
            $price,
            $amount,
            $couponId,
            $userNotes,
            $deduction,
            [
                'useSale'    => $useSale,
                'special_id' => intval(input('specialId', input('special_id', 0))),
            ],
            [
                'takeMobile' => $takeMobile,
                'takeTime' => $takeTime,
                'serviceId' => $serviceId,
            ],
        );
        return $this->result($info);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function offlineCheck(): bool
    {
        $orderNo = input('orderNo');
        $info = OrderLogic::getInstance()->offlineCheck($orderNo);
        return $this->result($info);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function checkOrderDetail(): bool
    {
        $orderNo = input('orderNo');
        $info = OrderLogic::getInstance()->checkOrderDetail($orderNo);
        return $this->result($info);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function checkList(): bool
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 10);
        $info = OrderLogic::getInstance()->checkList($page, $pageSize);
        return $this->result($info);
    }


}
